#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-07-23

@author: zhuyu
"""
import re
import time
import xlwt
import commands
import baseFunc
import threading


MEM_DIRS = '/Users/wangjianwen/Documents/rk3288Data/'
RUN_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.osupdate',
        'com.alipay.mapp.content.service',
        'com.alipay.iot.settings',
        'zoloz.phone.android.alipay.com.dragonfly',
        'com.alipay.zoloz.smile',
        'com.alipay.iot.xpaas',
        'com.alipay.mapp.content.service',
        'com.alipay.mapp.content.display',
        'com.alipay.iot.profile',
        'com.alipay.iot.merchantplugin',
        'com.alipay.iot.miniapp.shell',
        'com.alipay.iot.bootwizard'
        ]


def getAlipayApp():
    alipay_info = {}
    for app in RUN_APP_LIST:
        alipay_info[app] = 0
    return alipay_info


def proc_osmemory():
    mem_dict = {}
    mem_lines = commands.getoutput('adb shell cat /proc/meminfo')
    for mem in mem_lines.split('\n'):
        meminfo = mem.split(':')
        mem_dict[meminfo[0]] = meminfo[1].strip()
    time.sleep(2)
    return mem_dict


def get_app_pid(appname):
    app_pid = 0
    lines = commands.getoutput("adb shell ps |grep {} ".format(appname)).split('\n')
    if lines == ['']:
        return app_pid
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        appname_temp = pro_info[-1].strip('\n')
        if appname == appname_temp:
            return app_pid


def getAlipayCpu(pid):
    app_cpu = 0.0  # 默认为0，当无此进程时为0，无cpu开销
    if pid == 0:
        return app_cpu
    cmd = "adb shell top  -n 1 |grep {}".format(pid)
    lines = commands.getoutput(cmd).split('\n')
    for line in lines:
        lis = line.split(' ')
        while '' in lis:  # 将list中的空元素删除
            lis.remove('')
        if len(lis) < 1:
            break
        if pid == lis[0]:
            app_cpu = float(lis[4].strip('%'))
    return app_cpu


def getAppMemory(app_name):
    cmds = "adb shell dumpsys meminfo {}".format(app_name)
    lines = commands.getoutput(cmds).split('\n')
    total = "TOTAL"
    mem_data = 0  # 获取失败时，例如进程挂了，直接返回0
    for line in lines:
        if re.findall(total, line):  # 找到TOTAL 这一行
            lis = line.split(" ")  # 将这一行，按空格分割成一个list
            while '' in lis:  # 将list中的空元素删除
                lis.remove('')
            # print '{}:{}'.format(app_name, lis[1])
            mem_data = int(lis[1])
    return mem_data


def saveStartMemoryData(loop_num):
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    # 将工作簿以bookname命名并保存
    apps_info = getAlipayApp()
    apps = apps_info.keys()
    app_table = {}
    j = 1  # 从第二行开始写入内存数据
    try:
        sheet.write(0, 0, 'usedram')
        sheet.write(0, 1, 'available')
        for i in range(2, len(apps)+2):  # 从第三列开始写入列名称
            sheet.write(0, i, apps[i-2])  # 第一行按应用名写入
            app_table[apps[i-2]] = i  # 记录应用名和列的关系，防止错乱
        sheet.write(0, len(apps) + 2, "alipay_total")
        while j < loop_num:
            alipay_total = 0
            osm = proc_osmemory()
            memtotal = int(osm['MemTotal'].split(' ')[0])  # 获取总的内存
            available = int(osm['MemAvailable'].split(' ')[0])
            usedram = memtotal - available  # 获取当前剩余内存
            sheet.write(j, 0, usedram)
            sheet.write(j, 1, available)
            for app in apps:
                app_mem = getAppMemory(app)
                sheet.write(j, app_table[app], app_mem)  # 写入内存数据
                alipay_total = alipay_total + app_mem
            sheet.write(j, len(apps)+2, alipay_total)
            print '第{}次：{}'.format(j, app_table )
            j = j+1
    finally:
        book.save('{}AlipayMem_{}.xls'.format(MEM_DIRS, baseFunc.gettimestr()))


def saveStartCpuData(loop_num):
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    # 将工作簿以bookname命名并保存
    apps_info = getAlipayApp()
    apps = apps_info.keys()
    app_table = {}
    j = 1  # 从第二行开始写入CPU数据
    try:
        for i in range(len(apps)):  # 从第三列开始写入列名称
            sheet.write(0, i, apps[i])  # 第一行按应用名写入
            app_table[apps[i]] = i  # 记录应用名和列的关系，防止错乱
        sheet.write(0, len(apps), "alipay_total")
        while j < loop_num:
            alipay_total = 0
            for app in apps:
                if apps_info[app] == 0:
                    apps_info[app] = get_app_pid(app)  # 如果pid为初始化时的0，则每次均去更新pid
                cpu_data = getAlipayCpu(apps_info[app])
                sheet.write(j, app_table[app], cpu_data)
                alipay_total = alipay_total + cpu_data
            sheet.write(j, len(apps), alipay_total)
            print '第{}次：{}'.format(j, app_table)
            j = j + 1
    finally:
        book.save('{}AlipayCPU_{}.xls'.format(MEM_DIRS, baseFunc.gettimestr()))


def runThreadMonitor(loop_num):
    t1 = threading.Thread(target=saveStartMemoryData, args=(loop_num, ))
    t2 = threading.Thread(target=saveStartCpuData, args=(loop_num, ))
    t1.start()
    t2.start()
    t1.join()
    t2.join()


def startMonitor():
    lines = []
    while len(lines) <= 1:
        lines = commands.getoutput('adb devices').split('\n')
    print '{}开始监控性能'.format(baseFunc.gettimestr())
    runThreadMonitor(100)


if __name__ == '__main__':
    startMonitor()
